let heartBeatTimer=null;
let reconnectingTimer=null;

const WS_MODE={
    MESSAGE:'MESSAGE',
    HEART_BEAT:'HEART_BEAT'
}
class Ws extends WebSocket{
    constructor(url) {
        super(url);
        this.connectedStatus=false;
        this.wsUrl=url;

        this.init();
    }
    init(){
        this.bindEvent()
    }
    static create(url){
        return new Ws(url)
    }
    bindEvent(){
        this.addEventListener('open',this.handleOpen,false);
        this.addEventListener('close',this.handleClose,false);
        this.addEventListener('error',this.handleError,false);
        this.addEventListener('message',this.handleMessage,false);
    }
    handleOpen(){
        console.log('-----------client is connected---------')
        this.connectedStatus=true
        this.startHeartBeat()
    }
    handleClose(){
        console.log('-----------client is close---------')
        this.connectedStatus=false
        //如果心跳定时器存在，就清空
        if(heartBeatTimer){
            clearInterval(heartBeatTimer);
            heartBeatTimer=null
        }
        //如果重连延时任务存在，就清空
        if(reconnectingTimer){
            clearTimeout(reconnectingTimer);
            reconnectingTimer=null;
        }
        //断了线重连
        this.reconnect()
    }
    handleError(e){
        console.log('-----------client is error---------',e)
        this.connectedStatus=false
        this.reconnect()
    }
    handleMessage(data){
        const {mode,msg}=this.receiveMsg(data)
        switch (mode) {
            case WS_MODE.MESSAGE:
                console.log('-------MESSAGE-----',msg)
                break;
            case WS_MODE.HEART_BEAT:
                this.connectedStatus=true;
                console.log('--------HEAET_BEAT--------',msg)
                break;
            default:
                break;

        }
    }
    startHeartBeat(){
        //开启一个心跳检测的定时任务
        heartBeatTimer=setInterval(()=>{
            if(this.connectedStatus){
                this.sendMsg({
                    mode:WS_MODE.HEART_BEAT,
                    msg:'HEART_BEAT'
                })
            }else{
                clearInterval(heartBeatTimer);
                heartBeatTimer=null;
            }
            this.waitForResponse();
        },4000)
    }
    reconnect(){
        return new Promise(resolve => {
            reconnectingTimer=setTimeout(()=>{
                resolve(Ws.create(this.wsUrl))
            },3000)
        })
    }
    //模拟websocket 关闭服务
    waitForResponse(){
        this.connectedStatus=false;
        setTimeout(()=>{
            this.close();
        },2000)
    }
    //接受消息
    receiveMsg({data}){
        return JSON.parse(data);
    }
    //发送消息
    sendMsg(data){
        return this.send(JSON.stringify(data))
    }
}

export default Ws